package com.mxpio.erp.equipment.provider;

import cn.hutool.core.collection.CollectionUtil;
import com.mxpioframework.jpa.query.Criterion;
import com.mxpioframework.jpa.query.Operator;
import com.mxpioframework.jpa.query.SimpleCriterion;
import com.mxpioframework.security.access.datascope.provider.DataScapeProvider;
import com.mxpioframework.security.service.DeptService;
import com.mxpioframework.security.service.RbacCacheService;
import com.mxpioframework.security.util.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Author : 吴盼盼
 * @Datetime : 2022/11/3 15:44
 * @Desc :
 * @Modor :  Modifytime:
 * @modDesc : 维修人所属部门=当前账号部门及子部门
 */
@Component
public class DistributePersonDeptProvider implements DataScapeProvider {
    @Autowired
    private DeptService deptService;
    @Autowired
    private RbacCacheService rbacCacheService;
    @Override
    @Transactional(readOnly = true)
    public List<Criterion> provide() {
        String loginUsername = SecurityUtils.getLoginUsername();
        List<Criterion> appendCriterions = new ArrayList<>();
        if (StringUtils.isBlank(loginUsername)){
            appendCriterions.add(new SimpleCriterion("createTime", Operator.EQ,new Date(0)));//如果未匹配到过滤条件，则增加一个不能正常匹配到数据的条件
            return appendCriterions;
        }
        Set<String> deptCodeSet = SecurityUtils.getDeptCode();//用户所属部门列表，目前系统不支持多部门
        if (deptCodeSet.isEmpty()){
            appendCriterions.add(new SimpleCriterion("createTime", Operator.EQ,new Date(0)));
            return appendCriterions;
        }
        //根据当前用户的部门获取所属部门及子部门的编码
        List<String> deptCodeWithSubByCode = deptService.getDeptCodeWithSubByCode(deptCodeSet.iterator().next());
        List<String> deptUserList = new ArrayList<>();
        //查询所有用户的部门数据
        Map<String, Set<String>> allDeptCodeGroupByUser = rbacCacheService.getAllDeptCodeGroupByUser();
        for (String username: allDeptCodeGroupByUser.keySet()){
            Set<String> loopDeptCodeSet = allDeptCodeGroupByUser.get(username);
            if (CollectionUtil.isNotEmpty(loopDeptCodeSet)){
                //根据用户的部门编码反查用户
                if (deptCodeWithSubByCode.contains(loopDeptCodeSet.iterator().next())){
                    deptUserList.add(username);
                }
            }
        }
        if (deptUserList.isEmpty()){
            appendCriterions.add(new SimpleCriterion("createTime", Operator.EQ,new Date(0)));
            return appendCriterions;
        }
        appendCriterions.add(new SimpleCriterion("distributePersonId", Operator.IN, deptUserList));
        return appendCriterions;
    }
}
